package com.sh.多线程相关;

import java.util.concurrent.*;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class 线程池 {
    public static void main(String[] args) {

//        ExecutorService executorService = Executors.newFixedThreadPool(19 );
//        for (int i = 0; i < 100; i++) {
//            executorService.submit(() -> {
//                System.out.println(Thread.currentThread().getName());
//            });
//        }
//        executorService.shutdown();

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4, 60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                new CustomThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("执行完毕");
//        executor.shutdown();

    }

   static class CustomThreadFactory implements ThreadFactory{
        private int count = 0;
        private String namePrefix = "MyPool-Thread-";
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, namePrefix + count++);
            thread.setUncaughtExceptionHandler((t, e) -> {
                System.err.println("线程 " + t.getName() + " 抛出异常：" + e.getMessage());
            });
            return thread;
        }
    }
}

